package com.ys.service.account.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.account.TbAdvanceType;
import com.ys.entity.account.TcwAdvanceAccount;
import com.ys.entity.account.TcwAdvanceAccountDetail;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsGridCol;
import com.ys.mapper.account.TcwAdvanceAccountDetailMapper;
import com.ys.mapper.account.TcwAdvanceAccountMapper;
import com.ys.service.account.TcwAdvanceAccountService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 预支账户管理
 */
@Service("tcwAdvanceAccountService")
public class TcwAdvanceAccountServiceImpl implements TcwAdvanceAccountService {
	private static final Logger logger = LoggerFactory.getLogger(TcwAdvanceAccountServiceImpl.class);

	@Autowired
	private TcwAdvanceAccountMapper tcwAdvanceAccountMapper;

	@Autowired
	private TcwAdvanceAccountDetailMapper tcwAdvanceAccountDetailMapper;


	@Autowired
	private CheckUtil checkUtil;

	private final Long GRID = 15L;

	/**
	 * 新增
	 */
	@Override
	public R add(Map<String, Object> params, Long menuId) throws Exception {
		logger.info("传参："+params);
		//参数验证
		String errorMsg = checkParams(params,menuId);
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		TcwAdvanceAccount tcwAdvanceAccount = JSON.parseObject(JSON.toJSONString(params), TcwAdvanceAccount.class);
		tcwAdvanceAccountMapper.insert(tcwAdvanceAccount);
		return R.ok(EditDto.closeAndReload());
		//return R.ok(AddDto.gotoEdit("/web/finance/tbAdvanceType/toEdit?id=" + tbAdvanceType.getId()));
	}


	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params, Long menuId) throws Exception {
		logger.info("传参："+params);
		//参数验证
		String errorMsg = checkParams(params,menuId);
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		TcwAdvanceAccount tcwAdvanceAccount = JSON.parseObject(JSON.toJSONString(params), TcwAdvanceAccount.class);
		tcwAdvanceAccountMapper.update(tcwAdvanceAccount);
		//return R.ok();
		return R.ok(EditDto.closeAndReload());
	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCW_AdvanceAccount",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		if(checkUtil.isNotNullByObject(params.get("accountType")) && checkUtil.isNotNullByObject(params.get("accountTypeByModal"))){
			if(!params.get("accountType").equals(params.get("accountTypeByModal"))){
				backMsg = "账户性质和所选的银行账户不一致！";
			}
		}


		return backMsg;
	}



	/**
	 * 保存子表信息
	 */
	@Override
	public R toSaveItem(Map<String, Object> params) throws Exception {
		logger.info("传参："+params);

		Long userChangeId = null;
		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			userChangeId = tsUserChange.getId();//制单人变更信息
		}else {
			R.error("未查询到制单人信息！");
		}
		Long pid = null;

		List<Map<String, Object>> subDataList = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			CheckByGrid checkByGrid = checkParamsByGrid(subData,GRID,params);
			if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
				return R.error(checkByGrid.getErrMsg());
			}
			subDataList = checkByGrid.getSubDataList();
		}else {
			return R.error("列表信息为空！");
		}

		for (Map<String, Object> item:subDataList) {

			TcwAdvanceAccountDetail tcwAdvanceAccountDetail = JSON.parseObject(JSON.toJSONString(item), TcwAdvanceAccountDetail.class);
			pid = tcwAdvanceAccountDetail.getPid();
			BigDecimal quantity = tcwAdvanceAccountDetail.getQuantity()!=null?tcwAdvanceAccountDetail.getQuantity():BigDecimal.ZERO;//数量
			BigDecimal unitPrice = tcwAdvanceAccountDetail.getUnitPrice()!=null?tcwAdvanceAccountDetail.getUnitPrice():BigDecimal.ZERO;//单价
			//总额 = 单价 * 数量
			BigDecimal totalPrice = unitPrice.multiply(quantity);
			tcwAdvanceAccountDetail.setTotalPrice(totalPrice);//总额

			BigDecimal proxyPrice = tcwAdvanceAccountDetail.getProxyPrice()!=null?tcwAdvanceAccountDetail.getProxyPrice():BigDecimal.ZERO;//代理价
			//代理总额 = 代理价 * 数量
			BigDecimal proxyTotalPrice = proxyPrice.multiply(quantity);
			tcwAdvanceAccountDetail.setProxyTotalPrice(proxyTotalPrice);//代理总额

			if(tcwAdvanceAccountDetail.getId()!=null){
				TcwAdvanceAccountDetail oldInfo = new TcwAdvanceAccountDetail().setId(tcwAdvanceAccountDetail.getId()).queryFirst();
				if(oldInfo.getTransferStatus()==1){//已划拨:只可修改成本价、备注
					oldInfo.setUnitPrice(tcwAdvanceAccountDetail.getUnitPrice());
					oldInfo.setTotalPrice(tcwAdvanceAccountDetail.getTotalPrice());
					oldInfo.setRemark(tcwAdvanceAccountDetail.getRemark());
					//tcwAdvanceAccountDetail.setProxyPrice(oldInfo.getProxyPrice());
					//tcwAdvanceAccountDetail.setProxyTotalPrice(oldInfo.getProxyTotalPrice());
				}
				if(oldInfo.getDetailType()==1){//已报销:只可修改备注
					//tcwAdvanceAccountDetail.setUnitPrice(oldInfo.getUnitPrice());
					//tcwAdvanceAccountDetail.setTotalPrice(oldInfo.getTotalPrice());
					oldInfo.setRemark(tcwAdvanceAccountDetail.getRemark());
				}
				//修改
				if(oldInfo.getTransferStatus()==1 || oldInfo.getDetailType()==1){
					tcwAdvanceAccountDetailMapper.update(oldInfo);
				}else {
					tcwAdvanceAccountDetailMapper.update(tcwAdvanceAccountDetail);
				}
			}else {
				//新增
				tcwAdvanceAccountDetail.setCreateChangeId(userChangeId);
				tcwAdvanceAccountDetail.setStatus(1);
				tcwAdvanceAccountDetail.setTransferStatus(0);//划拨状态
				tcwAdvanceAccountDetail.setDetailType(0);
				tcwAdvanceAccountDetailMapper.insert(tcwAdvanceAccountDetail);
			}
		}
		//return R.ok();

		return R.ok(AddDto.gotoEdit("/web/account/tcwAdvanceAccount/toListByEdit?id=" + pid));
	}



	/**
	 * 子表参数验证
	 */
	public CheckByGrid checkParamsByGrid(JSONArray subDataArray, Long gridId, Map<String, Object> params) throws Exception {
		CheckByGrid checkByGrid = new CheckByGrid();
		//获取pc字段数据
		List<YsGridCol> listField = new YsGridCol()
				.setGridId(gridId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		String backMsg = "";
		List<Map<String, Object>> subDataList = new ArrayList<>();

		if(subDataArray!=null && subDataArray.size()>0){
			for (int i = 0; i < subDataArray.size(); i++) {
				JSONObject jsonObject = subDataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				subDataList.add(paramsNewByRecord);
			}
			//验证
			for(int i = 0;i<subDataList.size();i++){
				String backMsgByRow = "";
				Map<String, Object> subData = subDataList.get(i);
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsgByRow += checkUtil.checkTableColLengthAndDataTypeByGrid(
						"TCW_AdvanceAccountDetail",
						listField,
						subData,
						ysColItem->
								ysColItem.getCode().equals("pid")
										|| ysColItem.getCode().equals("companyInfoVid")
										|| ysColItem.getCode().equals("advanceTypeCode")
										|| ysColItem.getCode().equals("unitPrice")
										|| ysColItem.getCode().equals("quantity")
				);

				//代理价不能低于成本价
				if(checkUtil.isNotNullByObject(subData.get("detailType")) && checkUtil.isNotNullByObject(subData.get("transferStatus"))
				&& checkUtil.isNotNullByObject(subData.get("unitPrice")) && checkUtil.isNotNullByObject(subData.get("proxyPrice"))){
					if(subData.get("detailType").toString().equals("0") && subData.get("transferStatus").toString().equals("0")){
						BigDecimal unitPrice = new BigDecimal(subData.get("unitPrice").toString());//成本价
						BigDecimal proxyPrice = new BigDecimal(subData.get("proxyPrice").toString());//代理价
						if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 && proxyPrice.compareTo(unitPrice)<0){
							backMsgByRow += "代理价不能低于成本价";
						}
					}

				}
				if(checkUtil.isNotNullByObject(backMsgByRow)){
					backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
				}
			}
		}else{
			backMsg = "列表信息为空";
		}
		checkByGrid.setErrMsg(backMsg);
		checkByGrid.setSubDataList(subDataList);

		return checkByGrid;
	}




}
